<?php

namespace App\Services;

use App\Caches\PhoneCodeCache;
use App\Services\Sms\HuaweiSmsService;

class PhoneCodeService extends ServiceBase
{
    const PHONE_CODE_TYPE_REG      = 1;  //注册
    const PHONE_CODE_TYPE_LOGIN    = 2;  //登录
    const PHONE_CODE_TYPE_BIND     = 3;  //绑定
    const PHONE_CODE_TYPE_UNBIND   = 4;  //解绑
    const PHONE_CODE_TYPE_RETRIEVE = 5;  //找回

    const PHONE_CODE_LENGTH = 6; //验证码长度

    public function send($type, $phone)
    {
        $res = $this->create($type, $phone);
        if (!is_array($res)) {
            return $res;
        }

        $res = HuaweiSmsService::getInstance()->sendPhoneCode($phone, $res['code']);
        if (!$res) {
            $this->clear("{$type}_{$phone}");
            yqlog($res, $phone, $type);
            return 7007;
        }

        return true;
    }

    public function create($type, $phone)
    {
        $key   = "{$type}_{$phone}";
        $class = PhoneCodeCache::getInstance();
        if ($class->has($key)) {
            $one = $class->get($key);
            if ($one['created'] + 60 > time()) {
                return 7006;
            }
            $this->clear($key);
        }

        $one = $class->remember($key);
        if (empty($one)) {
            $this->clear($key);
            return -1;
        }

        return $one;
    }

    public function verify($type, $phone, $code)
    {
        $key = "{$type}_{$phone}";
        if (!PhoneCodeCache::getInstance()->has($key)) {
            return 7008;
        }

        $one = PhoneCodeCache::getInstance()->remember($key);
        if (empty($one)) {
            return -1;
        }

        if ($code != $one['code']) {
            return 7005;
        }

        //验证成功清除
        $this->clear($key);

        return true;
    }

    public function clear($key)
    {
        PhoneCodeCache::getInstance()->forget($key);
    }
}
